<?php
/**
 * display module actions.
 *
 * @package    Binova WF
 * @subpackage display
 * @author     Andr�s Lartigue Debi�n
 * @version    SVN: $Id: actions.class.php 12474 2008-10-31 10:41:27Z fabien $
 */

class baseDisplayActions extends sfActions
{
  function getClassName($request){  	
  	return $request->getParameter('className');
  }	
  
  public function executeIndex(sfWebRequest $request)
  {
  	
  	$className = $this->getClassName($request);
    $objDef = new objectDef($className);
	$this->className = $className;
	$this->action = 'index';
	$this->module = $this->getModuleName();
	$this->objDef = $objDef;     
	
  }

  
 public function executeRenderList(sfWebRequest $request)
  {
  	sfConfig::set('sf_web_debug', false);
  	$util = new Util();
    $className = $this->getClassName($request);
	$hide = array();
	$add = array();	
    
  	$orderByCol = $request->getParameter('order');
  	$page = (int)$request->getParameter('page',1);
    if(!isset($this->objDef)){
    	$this->objDef = new objectDef($className);	
    }
	
	$descCol = $this->objDef->descriptor;
	if(empty($orderByCol)){
  		if($descCol!=''){
  			$orderByCol =  $this->objDef->orderFields;
  			if($orderByCol=='') {
  				$orderByCol = $descCol.'*asc';	
  			}
  		}
  	}

  	$orderSens = 'asc';
	$orderArray = array();
    if(!empty($orderByCol)){
    	$arrayTmp = explode(';',$orderByCol);
    	foreach($arrayTmp as $orderString){
    		$orderColArray=explode('*',$orderString);
    		if(count($orderColArray)>0){
    			if(isset($orderColArray[1]))
    				$orderSens = $orderColArray[1];
    		}
    		$orderArray[] = $orderColArray;
    	}
    	
    }else{
    	$orderColArray=array();
    }
  	$orderArray[] = array('id',$orderSens);
  	if(!isset($this->q)){
	  	$this->q = $this->objDef->getBaseQuery($hide, $add, $orderArray);
		if($request->hasParameter('owner_id')){
			if(isset($this->objDef->attributes['owner_id'])){
				$this->q->addWhere('a.owner_id = ? ', $request->getParameter('owner_id'));
			}
		}	
  	}
	
	$search = new searchBar();	
	$search->addFilterstoQuery($this->q);
	$this->q->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY);
	$pager = $search->setPager($request, $this->q, 0, $page);
	$records = $pager->getResults(); 
	$addButton = !$this->objDef->isReadOnly;
	$orderParams = '1'; /*So it will go back to first page when users click to order by*/
	$module = $this->getModuleName();
	
  	return $this->renderPartial('display/itemslist', array('objDef' => $this->objDef,'records'=>$records, 'module'=>$module, 'hide' => $hide, 
  								'addButton' => $addButton, 'orderParams' => $orderParams, 'pager'=>$pager, 'orderByCol' => $orderByCol)); 
   }  

  public function executeShow(sfWebRequest $request)
  {
    $this->self = Doctrine::getTable($this->getClassName($request))->find($request->getParameter('id'));
    $this->forward404Unless($this->self, 'Object ' . $this->getClassName($request) . ' with id ' . $request->getParameter('id') . ' not found');
	$this->className = $this->getClassName($request);
	$this->module = $this->getModuleName();
	$this->objDef = new objectDef($this->className);     
	$this->owner_id = $request->getParameter('owner_id', null);
	if(!is_null($this->owner_id))
	{
		$ownerData = Util::getOwnerFieldAndClass($this->self, 'List');  
		$this->owner_field = $ownerData['ownerField'];
		$this->ownerClass = $ownerData['ownerClass'];
	}	
  }

  public function executeNew(sfWebRequest $request)
  {
  	$formClass = $this->getClassName($request).'Form';
    $this->form = new $formClass();
    $this->owner_id = $request->getParameter('owner_id', null);
    if(!is_null($this->owner_id))
    {

    	$owner_field = $this->form->getOwnerField('List');
    	$this->form->setDefault($owner_field, $this->owner_id);
    	$this->form->hideWidget(substr($owner_field, 0, strlen($owner_field)-3)); //hide widget. Use of substr to take out _id
    }
	$this->className = $this->getClassName($request);
	$this->module = $this->getModuleName();

	$this->objDef = new objectDef($this->className);
	$this->itemsForms = array();
  	if($this->objDef->hasAttach){
		$this->formAttach = new attachmentForm();
		$this->getUser()->setAttribute('filesToUpload', array());
	}
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod('post'));

  	$formClass = $this->getClassName($request).'Form';
    $this->form = new $formClass();
   	$this->owner_id = $request->getParameter('owner_id', null);
    if(!is_null($this->owner_id))
    {

    	$owner_field = $this->form->getOwnerField('List');
    	$this->form->setDefault($owner_field, $this->owner_id);
    	$this->form->hideWidget(substr($owner_field, 0, strlen($owner_field)-3)); //hide widget. Use of substr to take out _id
    }    
	$this->className = $this->getClassName($request);
	$this->module = $this->getModuleName();
    
    $this->processForm($request, $this->form);

	$this->objDef = new objectDef($this->className);
	$this->itemsForms = array();
  	if($this->objDef->hasAttach){
		$this->formAttach = new attachmentForm();
	}
    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($self = Doctrine::getTable($this->getClassName($request))->find($request->getParameter('id')), sprintf('Object does not exist (%s).', $request->getParameter('id')));
  	$formClass = $this->getClassName($request).'Form';
    $this->form = new $formClass($self);

  	$this->owner_id = $request->getParameter('owner_id', null);
    if(!is_null($this->owner_id))
    {
    	$owner_field = $this->form->getOwnerField('List');
    	$this->form->hideWidget(substr($owner_field, 0, strlen($owner_field)-3)); //hide widget. Use of substr to take out _id
    }
        
    $this->className = $this->getClassName($request);
	$this->module = $this->getModuleName();

	$this->objDef = new objectDef($this->className);

	if($this->objDef->hasAttach){
  		$q = Doctrine::getTable('attachment')
			->createQuery('m')
			->where('owner_id= ?',$self->id)
			->andWhere("ownerclass = ?",get_class($self));
		$records =	$q->execute();
  		$files = array();
  		foreach($records as $attachment){
  			$files[$attachment['file']] = $attachment;
  		}
		$this->formAttach = new attachmentForm();
		$this->getUser()->setAttribute('filesToUpload', $files);
	}
  }

  public function executeUpdate(sfWebRequest $request)
  {
  	$className = $this->getClassName($request);
    $this->forward404Unless($request->isMethod('post') || $request->isMethod('put'));
    $this->forward404Unless($self = Doctrine::getTable($className)->find($request->getParameter('id')), sprintf('Object does not exist (%s).', $request->getParameter('id')));
  	$formClass = $className.'Form';
    $this->form = new $formClass($self);
    $this->processForm($request, $this->form);
     
    $this->owner_id = $request->getParameter('owner_id', null);
    if(!is_null($this->owner_id))
    {
    	$owner_field = $this->form->getOwnerField('List');
    	$this->form->hideWidget(substr($owner_field, 0, strlen($owner_field)-3)); //hide widget. Use of substr to take out _id
    }    
    $this->itemsForms = array();
	$this->className = $className;
	$this->module = $this->getModuleName();
    
  	$this->objDef = new objectDef($this->className);

	if($this->objDef->hasAttach){
  		$q = Doctrine::getTable('attachment')
			->createQuery('m')
			->where('owner_id= ?',$self->id)
			->andWhere("ownerclass = ?",get_class($self));
		$records =	$q->execute();
  		$files = array();
  		foreach($records as $attachment){
  			$files[$attachment['file']] = $attachment;
  		}
		$this->formAttach = new attachmentForm();
		$this->getUser()->setAttribute('filesToUpload', $files);
	}
	
	$this->setTemplate('edit');
    
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($self = Doctrine::getTable($this->getClassName($request))->find($request->getParameter('id')), sprintf('Object sf_producto does not exist (%s).', $request->getParameter('id')));
	$this->owner_id = $request->getParameter('owner_id', null);
	if(!is_null($this->owner_id))
	{
		$ownerData = Util::getOwnerFieldAndClass($self, 'List');  
		$this->owner_field = $ownerData['ownerField'];
		$this->ownerClass = $ownerData['ownerClass'];
	}	    
    $self->delete();
    if(is_null($this->owner_id)){
    	$this->redirect($this->getModuleName().'/index?className='.$this->getClassName($request));
    }else{
    	$ownerModule = $this->getModuleName();
	    $this->redirect($ownerModule.'/show?id='.$this->owner_id.'&className='.$this->ownerClass);
	    
    }
    
  }

  protected function processForm(sfWebRequest $request, sfForm $form, $redirect = true)
  {
    //$form->bind($request->getParameter($form->getName()));
    $file = false;
	$params = $request->getParameter($form->getName());

  	$util = new Util;
  	$className = $this->getClassName($request);
	$objDef = new objectDef($className);
	$filesToUpld = array();
	//$itemsToSave = array();
	foreach($objDef->attributes as $fieldName => $att){
		if($att['show']){
			if($att['type']=='date'){
				$params[$fieldName] = $util->getDateFromStr($params[$fieldName]);
			}elseif($att['type']=='timestamp'){
				$params[$fieldName] = $util->getDateFromStr($params[$fieldName], true);
			}elseif($att['type']=='file' or $att['type']=='image'){
				 $file = true;
				 $filesToUpld[]=$fieldName;
			}
		}
		if($att['type']=='BOList'){
			$relatedObjectDef = new objectDef($att['relatedClass']);
			if(isset($params[$fieldName])){
				foreach ($params[$fieldName] as $key => $subFieldValue){
		    		foreach($relatedObjectDef->attributes as $relatedFieldName => $relatedAtt){
		    			if($relatedAtt['type']=='BO'){$relatedFieldName = $relatedFieldName.'_id';}
		    			
			    		if($relatedAtt['type']=='date'){
							$params[$fieldName][$key][$relatedFieldName] = $util->getDateFromStr($subFieldValue[$relatedFieldName]);
						}elseif($relatedAtt['type']=='timestamp'){
							$params[$fieldName][$key][$relatedFieldName]  = $util->getDateFromStr($subFieldValue[$relatedFieldName], true);
						}elseif($relatedAtt['type']=='file' or $att['type']=='image'){
							 $file = true;
							 //$filesToUpld[]=$relatedFieldName;
						}
		    			if (isset($subform[$relatedFieldName]) and $subform[$relatedFieldName]->hasError()){ 
		    					$errors .= $i18N->__('Error in the field : ') . $relatedAtt['label'].' ('.$relatedFieldName.')';
					    		foreach ($subform[$relatedFieldName]->getError() as $error){ 
						    			$errors .= ' * '.$error .'<br />';
					    		}
				    	}
		    					
		    		}
		    	}
			}
			//$itemsToSave[] = $this->getUser()->getAttribute('itemsList'.$fieldName);
		}
	}
	if($form->isMultipart()){
		$form->bind($params, $request->getFiles($form->getName()));
  	}else{
		$form->bind($params);
	}
    if ($form->isValid())
    {
    	$self = $form->save();
    	$this->owner_id = $request->getParameter('owner_id', null);
    	if(!is_null($this->owner_id))
    	{
    		$ownerData = Util::getOwnerFieldAndClass($self, 'List');
    		$owner_field = $ownerData['ownerField'];
    		$ownerClass = $ownerData['ownerClass'];
    		$self->$owner_field = $this->owner_id;
    		$self->save();
	    	$owner_id = $self->$owner_field;
	    	$ownerModule = $this->getModuleName();
	    	if($redirect)
	    	{
	    		$this->redirect($ownerModule.'/show?id='.$owner_id.'&className='.$ownerClass);
	    	}
	    	else 
	    	{
	    		
	    		return $self;
	    	}
	    }else{
	    	if($redirect)
	    	{
	    		$this->redirect($this->getModuleName().'/index?className='.$this->getClassName($request));	
	    	}
	    	else 
	    	{
	    		return $self;
	    	}
	    	
	    }
    }else{
    	$util->sendDebug('Invalid Form: ', 2);
		$i18N = sfContext::getInstance()->getI18N();
    	$errors = '';
    	if($form->renderGlobalErrors()!=''){
    		$errors = $i18N->__('Form Errors: ').$form->renderGlobalErrors().'<br />';
    	}
   		 foreach($objDef->attributes as $fieldName => $att){
    		if($att['type']!='List' and $att['type']!='function' and $att['type']!='CheckboxList'){
	    		if($att['type']=='BO'){$fieldName = $fieldName.'_id';}
	    		if($att['type']=='BOList'){
	    			$relatedObjectDef = new objectDef($att['relatedClass']);
	    			foreach ($form[$fieldName] as $subform){
	    				foreach($relatedObjectDef->attributes as $relatedFieldName => $relatedAtt){
	    					if($relatedAtt['type']=='BO'){$relatedFieldName = $relatedFieldName.'_id';}
		    				if (isset($subform[$relatedFieldName]) and $subform[$relatedFieldName]->hasError()){ 
		    					$errors .= $i18N->__('Error in the field : ') . $relatedAtt['label'].' ('.$relatedFieldName.')';
					    		foreach ($subform[$relatedFieldName]->getError() as $error){ 
						    			$errors .= ' * '.$error .'<br />';
					    		}
			    			}	
	    					
	    				}
	    			}
	    		}else{
		    		if (isset($form[$fieldName]) and $form[$fieldName]->hasError()){ 
		    			$errors .= $i18N->__('Error in the field : ') . $att['label'].' ('.$fieldName.')';
			    		foreach ($form[$fieldName]->getError() as $error){ 
				    			$errors .= ' * '.$error .'<br />';
			    		}
		    		}	
	    		}
    		}
    	}
    	$util->sendDebug('Form Errors: ' . $errors, 2);
    	//echo $errors;
    	//renderError() 
    	
    	$this->getUser()->setFlash('Error', $i18N->__('Invalid Form:'). '<br />'.$errors);
    	
    }
	
  }
  
  public function executeGetViewItems(sfWebRequest $request){
  	sfConfig::set('sf_web_debug', false);
	$this->getUser()->setAttribute('list_items', array());
    $ownerClass = $request->getParameter('ownerClass');
    $ownerId = $request->getParameter('ownerId');
    Util::sendDebug('Owner_id' . $ownerId, 2);
    $fieldName = $request->getParameter('fieldName');
    $className = $request->getParameter('className');
   	$objDef = new objectDef($className);
    $items = $this->getUser()->getAttribute('itemsList'.$fieldName);
    if(isset($items))
    { //Check if it's the correct Owner
    	if(count($items)>0){
    		//Util::sendDebug('Tengo items del owner' . $items[0]['owner_id'], 2);
    
    		if($items[0]['owner_id']!=$ownerId and $items[0]['owner_id'] != ''){
    			unset($items);
    		}
    	}
    }
    if(!isset($items)){
		/*It's the first time. Got to get the items from the database.*/
		$items = array();
	    $descCol = "id";
	    
	    $objDef = new objectDef($className);
	    $descCol = $objDef->descriptor;
		$q = Doctrine::getTable($className )
	      ->createQuery('a')
	       ->orderBy('a.'.$descCol)
	     ;
	     if($ownerId===''){
	     	$q->where('id is null'); //Force an empty view, because it's a new object.
	     }else{
	     	$q->where('owner_id = ?',$ownerId);
	     }
	     
		$results = $q->execute();
		foreach($results as $item){
			$items[]=$item;
		}
		$this->getUser()->setAttribute('itemsList'.$fieldName,$items);
	}
	
	//$html = $this->renderArray($className, $fieldName);
	//$iconsSize = sfConfig::get('app_defaultViewer_iconssize', '16');
	$html =  $objDef->renderListTable($items, 'defaultViewer', array(), false, true, true, false, '', false, false, true, $fieldName);		
	
  	return $this->renderText($html) ;
  }
  
  public function executeAddItem(sfWebRequest $request){
  		sfConfig::set('sf_web_debug', false);
		$i18N = sfContext::getInstance()->getI18N();
		$this->forward404unless($request->isXmlHttpRequest());
  		$number = intval($request->getParameter("num"));
		$fieldname = $request->getParameter("fieldname");
		$ownerClassname = $request->getParameter("ownerclass");
		$formClassname = $ownerClassname . 'Form';
		if($owner = Doctrine::getTable($ownerClassname)->find($request->getParameter('id'))){
		   $form = new $formClassname($owner);
		}else{
		   $form = new $formClassname(null);
		}
	
		$form->addItem($fieldname, $number);
		$objDef = new objectDef($ownerClassname);
		$att = $objDef->attributes[$fieldname];
		$relatedObjDef = new objectDef($att['relatedClass']);
		return $this->renderPartial('display/itemForm',array('form' => $form[$fieldname][$number], 'num' => $number, 'ownerFieldname' => $fieldname, 'objDef'=>$relatedObjDef, 'style'=>'display:none'));
  }
  
  public function executeDeleteItem(sfWebRequest $request){
  		sfConfig::set('sf_web_debug', false);
		$i18N = sfContext::getInstance()->getI18N();
		$this->forward404unless($request->isXmlHttpRequest());
  		$number = intval($request->getParameter("num"));
		$fieldname = $request->getParameter("fieldname");
		$ownerClassname = $request->getParameter("ownerclass");
		$formClassname = $ownerClassname . 'Form';
		if($owner = Doctrine::getTable($ownerClassname)->find($request->getParameter('id'))){
		   $form = new $formClassname($owner);
		}else{
		   $form = new $formClassname(null);
		}
	
		$form->addItem($fieldname, $number);
	
	return $this->renderPartial('itemForm',array('form' => $form[$fieldname][$number], 'num' => $number, 'ownerFieldname' => $fieldname));
  }  
  
  private function renderArray($className, $fieldName = ''){

	$objDef = new objectDef($className);
  	$module = 'defaultViewer';
  	$html = ''; 
  	$html .= '<table><thead><tr>';
    $html .=  '<th>'.'</th>';

    foreach($objDef->attributes as $att){
      if($att['list']){
      	$html .= '<th>'.$att['label'].'</th>';
      }
    }  
    
    $html .= '</tr></thead><tbody>';
    foreach ($this->getUser()->getAttribute('itemsList'.$fieldName) as $item){
	    $html .= '<tr>';
	    $html .=  '<td width="112px">'. link_to('<img src="/images/icons/32/show.png"/>', $module. '/show?id='.$item->id);
	      	  if(!$objDef->isReadOnly) { $html .=  link_to('<img src="/images/icons/32/edit.png"/>', $module.'/edit?id='.$item->id);}
	      	  if($objDef->canBeDeleted) {$html .=  link_to('<img src="/images/icons/32/delete.png"/>', $module.'/delete?id='.$item->id);}
	    $html .=  '</td>';
	    foreach($objDef->attributes as $fieldName => $att){
	    	if($att['list']){
	    	    $html .=  '<td>';
	    		if($att['type']=='object'){
	    	    	if($item->getTable()->hasRelation($fieldName)){
	    	    		$classname2 = $item->$fieldName->getTable()->getOption('name');
	    	    		$relatedObjDef = new objectDef($classname2);
	    	    		$descriptor = $relatedObjDef->descriptor;
	    	    		$html .=  $item->$fieldName->$descriptor;
	    	    	} 
	    	    }else{
	      			$html .= $item->$fieldName;
	      		}
	      		$html .=  '</td>';
	    	}
	    }
	    $html .=  '</tr>';
	}
	$html .=  '</tbody>';
	$html .=  '</table>';
	    
  	return $html;
  }
  

  public function executeExport(sfWebRequest $request)
	{
		set_time_limit(0);
		sfContext::getInstance()->getLogger()->debug(" inicio memory usage: " . (memory_get_usage(true) / 1024 / 1024) . " MB");
		$format = $request->getParameterHolder()->get('format', 'csv');
		$allFields = $request->getParameterHolder()->get('allFields', 'false');

		$dateFormatter = new sfDateFormat($this->getUser()->getCulture());
		ini_set('memory_limit', '1024M');
		
    	$className = $this->getClassName($request);
		$objDef = new objectDef($className);
		$util = new Util();
		$charset = $util->getCharset();
  		$nb_colonne = count($objDef->attributes);
  		
  		$orderByCol = $request->getParameter('order');
    
		$descCol = $objDef->descriptor;
      
	  	if(empty($orderByCol)){
	  		if($descCol!=''){
	  			$orderByCol = $descCol.'*asc';	
	  		}
	  	}
	
	  	$orderSens = 'asc';
	
	    if(!empty($orderByCol)){
	    	$orderColArray=explode('*',$orderByCol);
	    	if(count($orderColArray)>0){
	    		if(isset($orderColArray[1]))
	    			$orderSens = $orderColArray[1];	
	    	}
	    }else{
	    	$orderColArray=array();
	    }  
		// $hide est un array avec des champs que on ne veut pas exporter
		$add = array();
		$hide = array();
	    
    	$q = $objDef->getBaseQuery($hide, $add, array($orderColArray,array('id',$orderSens)));
		$search = new searchBar();	
		$search->addFilterstoQuery($q);
		//Util::sendDebug($q->getSqlQuery());
		
		$q->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY);
  		
  		
  		// Execute la requete
		sfContext::getInstance()->getLogger()->debug(" after query memory usage: " . (memory_get_usage(true) / 1024 / 1024) . " MB");

		$col = 2;
		
		if($format=='csv'or$format=='xls'){
			$pathTemp = sfConfig::get('sf_temp_dir', '/temp/');
			$nomFichier = $util->createGUID();
			$path = $pathTemp . DIRECTORY_SEPARATOR.$nomFichier.'.'.$format;
		}
		
		$results = $q->execute();
		$count = count($results);
		sfContext::getInstance()->getLogger()->debug(" after execute memory usage: " . (memory_get_usage(true) / 1024 / 1024) . " MB");
		
		if($format=='csv'){
			$separator = ';';
			
			$fh = fopen($path, 'w');

			$lig = 1;
  			
  			foreach($objDef->attributes as $fieldName => $att)
			{
				if(($att['list'] and !in_array($fieldName, $hide) and $att['type'] != 'List')or(in_array($fieldName,$add))or($allFields=='true'))
				{
					$nouvLabel = utf8_decode($util->stripCaract($att['label'],true));
					fwrite($fh, $nouvLabel .$separator);
				}
			}
			fwrite($fh, "\n");
			$lig = 2;
			foreach($results as $ligne)
			{
					//sfContext::getInstance()->getLogger()->debug($ligne->id);
					foreach($objDef->attributes as $fieldName => $att)
					{
						if(($att['list'] and !in_array($fieldName, $hide) and $att['type'] != 'List')or(in_array($fieldName,$add)or($allFields=='true')))
						{
							if($att['type']=='blob'){
								if($charset=='utf8'){
									$value = utf8_decode($ligne[$fieldName]);
								}else{
									$value = $ligne[$fieldName];
								}
							}
							else
							{
								if($charset=='utf8'){
									$value = utf8_decode($objDef->renderAttributeValue($ligne,$fieldName));
								}else{
									$value = $objDef->renderAttributeValue($ligne,$fieldName);
								}
							}
						    
							/*if($att['type']=='date'){ 
								echo $dateFormatter->format($ligne->$fieldName, 'd/M/y', null, $objDef->charset);
							}else{
								echo utf8_decode($ligne->$fieldName);
							}*/
							
							$value = str_replace($separator,'_',$value);
							$value = str_replace(chr(10),"*",$value);						    
							$value = str_replace(chr(13),"*",$value);
						    fwrite($fh, $value.$separator);
							$col++;
							unset($value);
							unset($fieldName);
							unset($att);
						}
					}
					unset($ligne);
					fwrite($fh, "\n");
					//unset($col);
					$lig++;
					
				}
			sfContext::getInstance()->getLogger()->debug(" Peak memory usage: " . (memory_get_peak_usage(true) / 1024 / 1024) . " MB");

			fclose($fh);
			
		}elseif($format=='table' or $format=='html'){
			    	
			$response = $this->getContext()->getResponse(); 
			$this->getResponse()->clearHttpHeaders(); 
			//$this->getResponse()->setHttpHeader('Content-Type', 'application/vnd.ms-excel;charset=utf-8');
			if($format=='html'){
				$this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename="export.html"');
			}else{
				$this->getResponse()->setContentType('application/msexcel', true);
				//$this->getResponse()->setHttpHeader('Content-Disposition:', 'attachment; filename=export.xls');     	
				$this->getResponse()->setHttpHeader('Content-Disposition', 'attachment; filename="export.xls"');
				$this->getResponse()->setContentType('application/msexcel', true);		
			}
			$this->allFields = $allFields;
		}elseif($format=='xls'){
			$objPHPExcel = new sfPhpExcel();
			
			// Set properties
			//$objPHPExcel->getProperties()->setCreator($pers->name);
			//$objPHPExcel->getProperties()->setLastModifiedBy($pers->name);
			$objPHPExcel->getProperties()->setTitle("Export e-DSL");
			$objPHPExcel->getProperties()->setSubject("e-DSL Excel Document");
			$objPHPExcel->getProperties()->setDescription("e-DSL Excel Document.");
			$objPHPExcel->getProperties()->setKeywords("e-DSL");
			$objPHPExcel->getProperties()->setCategory("e-DSL Excel Document");
			$objPHPExcel->getActiveSheet()->freezePane('B2');
			$objPHPExcel->setActiveSheetIndex(0);
			
			$col = ord("A");
			$lig = 1;
  			
  			foreach($objDef->attributes as $fieldName => $att)
			{
				if(($att['list'] and !in_array($fieldName, $hide) and $att['type'] != 'List')or(in_array($fieldName,$add))or($allFields=='true'))
				{
					$nouvLabel = $util->stripCaract($att['label']);
					$objPHPExcel->getActiveSheet()->setCellValue(chr($col) . $lig, $nouvLabel);
					$objPHPExcel->getActiveSheet()->getStyle(chr($col) . $lig)->getFont()->setName('Cambria');
					//$objPHPExcel->getActiveSheet()->getStyle(chr($col) . $lig)->getFont()->setSize(12);
					$objPHPExcel->getActiveSheet()->getStyle(chr($col) . $lig)->getFont()->setBold(true);
					$objPHPExcel->getActiveSheet()->getStyle(chr($col) . $lig)->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
					$objPHPExcel->getActiveSheet()->getStyle(chr($col) . $lig)->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_DARKBLUE);
					
					$col++;
				}
			}
			
			$lig = 2;
			foreach($results as $ligne)
			{
					$col = ord("A");
					//sfContext::getInstance()->getLogger()->debug($ligne->id);
					foreach($objDef->attributes as $fieldName => $att)
					{
						if(($att['list'] and !in_array($fieldName, $hide) and $att['type'] != 'List')or(in_array($fieldName,$add))or($allFields=='true'))
						{
						    $value = $objDef->renderAttributeValue($ligne,$fieldName);
							$objPHPExcel->getActiveSheet()->setCellValue(chr($col) . $lig, $value);
							$col++;
							unset($value);
						}
					}
					
					//sfContext::getInstance()->getLogger()->debug(" memory usage: " . (memory_get_usage(true) / 1024 / 1024) . " MB");
					unset($col);
					$lig++;
			}
			sfContext::getInstance()->getLogger()->debug(" Peak memory usage: " . (memory_get_peak_usage(true) / 1024 / 1024) . " MB");

			// Rename sheet
			$objPHPExcel->getActiveSheet()->setTitle($className);
			
			// Set active sheet index to the first sheet, so Excel opens this as the first sheet
			$objPHPExcel->setActiveSheetIndex(0);
			
			
			// Save Excel 2007 file

			
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			$objWriter->save($path);
			sfContext::getInstance()->getLogger()->debug("  Done writing Excel file");
		}
		if($format=='csv'or$format=='xls'){
	       	$response = $this->getResponse();
            $response->clearHttpHeaders();
            $response->setHttpheader('Pragma: public', true);
            $response->addCacheControlHttpHeader('Cache-Control', 'must-revalidate');
            $response->setHttpHeader('Expires', 'Sat, 26 Jul1997 05:00:00 GMT');
            $response->setHttpHeader("Last-Modified", gmdate("D, d M Y H:i:s") . " GMT");
            $response->setContentType('application/octet-stream', true);
            $response->setHttpHeader('Content-Description','File Transfer');
            $response->setHttpHeader('Content-Transfer-Encoding', 'binary', true);
            $response->setHttpHeader('Content-Length', filesize($path));
            $response->setHttpHeader('Content-Disposition','attachment; filename=export.'.$format);
            // Unlock session in order to prevent php sessionwarnings
            $this->getUser()->shutdown();
            // Send http headers to user client
            $response->sendHttpHeaders();
            // Send file to user client
            $response->setContent(file_get_contents($path));
            // $response->setContent(file_get_contents(utf8_decode($file->getPath())));
            // $response->sendContent();
            // Exit without a template
	        unlink($path);			
            return sfView::NONE;	
		}
		$this->format= $format;
		$this->setLayout(false);
		$this->hide =$hide;
		$this->add =$add;
    	//My query
    	$this->results = $results;
 		$this->objDef = $objDef;
 		return sfView::NONE;
	}

  
}
